<template>
  <div>
    <div class="seach">
      <input type="text" v-model="keyWord" placeholder="输入城市名或拼音" />
    </div>
    <div class="seach-list" v-show="keyWord">
      <ul>
        <li
          v-for="item of list"
          :key="item.id"
          @touchstart="handleTouchStart"
          @touchmove="handleTouchMove"
          @touchend="handleTouchEnd(item.name)"
        >
          {{item.name}}
        </li>
        <li v-show="noData">没有找到匹配数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
import BScroll from 'better-scroll'
import { mapMutations } from 'vuex'
export default {
  data () {
    return {
      keyWord: '',
      list: [],
      timer: null,
      touchStatus: false
    }
  },
  props: {
    cities: Object
  },
  computed: {
    noData () {
      return !this.list.length
    }
  },
  mounted () {
    this.scroll = new BScroll('.seach-list')
  },
  methods: {
    handleTouchStart () {
      this.touchStatus = true
    },
    handleTouchMove () {
      this.touchStatus = false
    },
    handleTouchEnd (city) {
      if (this.touchStatus) {
        // this.$store.dispatch('changeCity', city)  // 如果没有异步请求和批量操作，可省略这步，直接使用commit提交到mutations
        // this.$store.commit('changeCity', city) // 使用mapState之后，该方法可直接改写下面的格式
        this.touchStatus = false
        this.changeCity(city)
        this.$router.push('/')
      }
    },
    // 使用mapMutations，把this.changeCity(city) 映射给了 this.$store.commit('changeCity', city)
    ...mapMutations(
      ['changeCity']
    )
  },
  watch: {
    keyWord () {
      if (!this.keyWord) {
        this.list = []
      }
      // 使用定时器截流函数，提高性能
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        let result = []
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            if (value.spell.indexOf(this.keyWord) > -1 || value.name.indexOf(this.keyWord) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 100)
    }
  }
}
</script>

<style lang="stylus" scoped>
@import "~_style/var.styl"
.seach
  width:100%
  box-sizing:border-box
  padding:.1rem
  background:$bgColor
  input
    width:100%
    line-height:.72rem
    background:#fff
    border-radius:.1rem
    padding: 0 .1rem
    text-align:center
    color:#777
    box-sizing: border-box;
.seach-list
  width:100%
  overflow:hidden
  position:absolute
  z-index:3
  top:1.78rem
  bottom:0
  left:0
  right:0
  background:#fff
  li
    border-bottom:1px solid #eee
    line-height:.66rem
    padding:0 .2rem
</style>
